import { createI18n } from 'vue-i18n';
import en from './locales/en.json';
import zh from './locales/zh.json';
const messages = {
  en: {
    ...en
  },
  zh: {
    ...zh
  }
};
const getInitialLocale = () => {
  const savedLocale = localStorage.getItem('user-language');
  if (savedLocale) {
    return savedLocale;
  }

  // 检测浏览器语言
  const browserLang = navigator.language.toLowerCase();
  if (browserLang.includes('zh')) {
    return 'zh';
  } else {
    return 'en';
  }
};
const i18n = createI18n({
  legacy: false,
  locale: getInitialLocale(),
  fallbackLocale: 'en',
  globalInjection: true,
  messages
});
// 语言切换
export const changeLocale = (locale) => {
  i18n.global.locale.value = locale;
  localStorage.setItem('user-language', locale);
};

// 获取当前语言
export const getCurrentLocale = () => {
  return i18n.global.locale.value;
};

if (typeof window !== 'undefined') {
  window.addEventListener('storage', (event: StorageEvent) => {
    if (
      event.key === 'user-language' &&
      event.newValue &&
      event.newValue !== i18n.global.locale.value
    ) {
      i18n.global.locale.value = event.newValue;
    }
  });
}
export const availableLocales = [
  { code: 'en', name: 'English' },
  { code: 'zh', name: '中文' }
];
export default i18n;
